<template>
  <el-dialog v-model="dialogVisible" :destroy-on-close="true" width="450px" :title="`${dialogProps.title}用户`">
    <el-form
      ref="ruleFormRef"
      label-width="100px"
      label-suffix=" :"
      :rules="env.VITE_RELEASE_NAME === 'fendi' ? rules1 : rules2"
      :disabled="dialogProps.isView"
      :model="dialogProps.row"
      :hide-required-asterisk="dialogProps.isView"
    >
      <el-form-item label="账号" prop="userName">
        <el-input v-model="dialogProps.row!.userName" placeholder="请输入" disabled></el-input>
      </el-form-item>
      <el-form-item label="账号类型" prop="userType">
        <el-select class="w100" v-model="dialogProps.row!.userType" disabled>
          <el-option v-for="item in accountType" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="昵称" prop="nickName">
        <el-input v-model="dialogProps.row!.nickName" placeholder="请输入" clearable></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-radio-group v-model="dialogProps.row!.sex">
          <el-radio :label="item.value" v-for="item in genderType" :key="item.value">{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="dialogProps.row!.phone" placeholder="请输入" clearable></el-input>
      </el-form-item>
      <el-form-item label="初始密码" prop="defaultPassWord">
        <el-input v-model="dialogProps.row!.defaultPassWord" placeholder="请输入" clearable></el-input>
      </el-form-item>
      <el-form-item label="角色" prop="roles" v-if="dialogProps.row!.registerFlag !== 0">
        <el-checkbox-group v-model="dialogProps.row!.roles">
          <el-checkbox v-for="role in RoleList" :key="role.id" :label="role.id">{{ role.roleName }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false"> 取消 </el-button>
      <el-button v-show="!dialogProps.isView" type="primary" @click="handleSubmit"> 确定 </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts" name="StaffDialog">
import { ref, reactive } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { Operation } from "@/api/interface";
import { genderType, accountType } from "@/utils/serviceDict";
import { getDepartMentList } from "@/api/modules/operation";
import { getRoleList } from "@/api/modules/system";

const env = ref(import.meta.env);
// 密码校验
const validatePass = (rule: any, value: any, callback: any) => {
  const finalCheckPwd =
    /^(?:(?=.*[a-z])(?=.*[A-Z])(?=.*\d)|(?=.*[a-z])(?=.*[A-Z])(?=.*[\W_])|(?=.*[a-z])(?=.*\d)(?=.*[\W_])|(?=.*[A-Z])(?=.*\d)(?=.*[\W_])|(?=.*[A-Z])(?=.*[a-z])(?=.*[\W_])|(?=.*[A-Z])(?=.*[a-z])(?=.*\d)).{8,}$|^$/;

  // 校验密码
  const checkPwd: boolean = finalCheckPwd.test(dialogProps.value.row!.defaultPassWord);

  if (!checkPwd) {
    callback(new Error("密码必须不少于8位, 包含大小写、字母、字符至少三种"));
  } else {
    callback();
    // 注意，这个空的callback非常重要，没有它作为结束，整个校验会出问题
  }
};

const rules1 = reactive({
  // userName: [{ required: true, message: "请输入账号" }],
  userType: [{ required: true, message: "请选择账号类型" }],
  nickName: [{ required: true, message: "请输入昵称" }],
  sex: [{ required: true, message: "请选择性别" }],
  phone: [{ required: true, message: "请输入手机号" }],
  defaultPassWord: [{ required: true, trigger: "blur", validator: validatePass }]
});

const rules2 = reactive({
  // userName: [{ required: true, message: "请输入账号" }],
  userType: [{ required: true, message: "请选择账号类型" }],
  nickName: [{ required: true, message: "请输入昵称" }],
  sex: [{ required: true, message: "请选择性别" }],
  phone: [{ required: true, message: "请输入手机号" }],
  defaultPassWord: [{ required: true, trigger: "blur", message: "请输入" }]
});
const RoleList = ref([]);

interface DialogProps {
  title: string;
  isView: boolean;
  row: Partial<Operation.ResDepartmentList>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

const dialogVisible = ref(false);
const dialogProps = ref<DialogProps>({
  isView: false,
  title: "",
  row: {}
});

const department = ref([]);

// 接收父组件传过来的参数
const acceptParams = (params: DialogProps) => {
  dialogProps.value = params;
  dialogVisible.value = true;
  if (dialogProps.value.title === "新增") {
    dialogProps.value.row!.userType = 1;
    dialogProps.value.row!.defaultPassWord = "";
    dialogProps.value.row!.sex = 1;
  }
  getDepartMentList({ pageNum: 1, pageSize: 9999 }).then(res => {
    department.value = res.data.list;
  });
  getRoleList({ pageNum: 1, pageSize: 9999 }).then(val => {
    RoleList.value = val.data.list;
  });
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      await dialogProps.value.api!(dialogProps.value.row);
      ElMessage.success({ message: `${dialogProps.value.title}用户成功！` });
      dialogProps.value.getTableList!();
      dialogVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

defineExpose({
  acceptParams
});
</script>
